<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <dj-region @provVal="provVal" @cityVal="cityVal" @areaVal="areaVal" ref="region"></dj-region>
        </el-form-item>
        <!-- 状态栏 -->
        <el-form-item>
          <el-select filterable v-model="statusdefa">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="选择门店" v-model="formInline.store_id">
            <el-option v-for="item in store_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="编号" prop="ids">
          <template slot-scope="scope"><span>{{scope.row.serial_number}}</span></template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="name"></el-table-column>
        <el-table-column align="center" label='地址' prop="address"></el-table-column>
        <el-table-column align="center" label="所属产品" prop="orz_name">
          <template slot-scope="scope">{{scope.row.brand_name}}</template>
        </el-table-column>
        <el-table-column align="center" label='经纬度'>
          <template slot-scope="scope">{{scope.row.longitude}}/{{scope.row.latitude}}</template>
        </el-table-column>
        <el-table-column align="center" label='状态' prop="status" width="100">
          <template slot-scope="scope">
            <el-button @click="dialogVisibles(scope.row.id,scope.row)" v-if="scope.row.s_status==2" type="success" size="small">营业中 </el-button>
            <el-button @click="dialogVisibles(scope.row.id,scope.row)" v-if="scope.row.s_status==1" type="warning" size="small">待开业 </el-button>
            <el-button @click="dialogVisibles(scope.row.id,scope.row)" v-if="scope.row.s_status==3" type="warning" size="small">已停业 </el-button>
            <el-button @click="dialogVisibles(scope.row.id,scope.row)" v-if="scope.row.s_status==4" type="success" size="small">待闭店 </el-button>
            <el-button @click="dialogVisibles(scope.row.id,scope.row)" v-if="scope.row.s_status==5" type="warning" size="small">已闭店 </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="采购对接人" prop="pickuppeople" style="color:#409EFF">
          <template slot-scope="scope" style="color:#409EFF">
            <el-button @click="toconfigpeople(scope.row)" type="text" size="small">配置对接人</el-button>
          </template>
        </el-table-column>

        <el-table-column align="center" label="区域管理" width="100">
          <template slot-scope="scope">
            <el-button @click="areaDetailDelClick(scope.row.id)" type="text" size="small">查看详情</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label='机台列表' width="100">
          <template slot-scope="scope">
            <router-link :to="{name:'information/machine_list',params :{brand_id:scope.row.brand_id,store_id:scope.row.id,routerflag:1}}">
              <el-button type="text" size="small">查看详情</el-button>
            </router-link>
          </template>
        </el-table-column>

        <el-table-column align="center" label="微信小程序" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_switch" @change="changeClick(scope.row,1)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column align="center" label="支付宝小程序" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.zfb_switch" @change="changeClick(scope.row,2)"></el-switch>
          </template>
        </el-table-column>

        <!-- 列表的操作按钮 -->
        <el-table-column align="center" label="操作" width="310">
          <template slot-scope="scope">
            <el-button @click="addEditStoreClick(scope.row.id,scope.$index,scope.row)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <el-button type="primary" class="el-icon-more" @click="detail(scope.row.id)" size="mini">

            </el-button>
            <el-button type="primary" class="el-icon-share" @click="assHouseClick(scope.row.id,scope.$index)" size="mini"></el-button>
            <el-button type="primary" class="el-icon-download" size="mini" @click="downloadClick(scope.row.id,scope.row.name)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delStoreClick(scope.row.id,scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 点击详情弹窗 -->
      <el-dialog :close-on-click-modal="false" width="760px" class="storeDialog" title="门店信息详情" :visible.sync="opendetailDia" @close="callOf('storeForm')">
        <el-form :model="storeForm" ref="storeForm" :rules="rules" class="demo-form-inline">

          <el-form-item label="门店名称" prop="name" :label-width="formLabelWidth" style="display: inline-block;width:45%;margin-bottom: 0px;">
            <el-input type="text" disabled v-model="storeForm.name"></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:8%">
          </el-form-item>
          <el-form-item label="门店编号" prop="name" :label-width="formLabelWidth" style="display: inline-block;width:45%">
            <el-input type="text" disabled v-model="storeForm.serial_number"></el-input>
          </el-form-item>

          <el-form-item label="地址" prop="address" :label-width="formLabelWidth" style="width:45%;display: inline-block;vertical-align:top;">
            <div>
              <el-input disabled size="mini" v-model="bug_prov" style="width:80px"></el-input>
              <el-input disabled size="mini" v-model="bug_city" style="width:80px"></el-input>
              <el-input disabled size="mini" v-model="bug_area" style="width:75px"></el-input>
            </div>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:8%">
          </el-form-item>
          <el-form-item label="详细地址" prop="name" :label-width="formLabelWidth" style="width:45%;display: inline-block;">
            <el-input type="textarea" :rows="5" disabled v-model="storeForm.address"></el-input>
          </el-form-item>
          <!-- 经纬度 -->
          <div class="longloat">
            <el-form-item label="经/纬度" prop="position" :label-width="formLabelWidth" style="width:92%;vertical-align:top;margin-bottom: 0px">
              <el-input type="text" disabled v-model="storeForm.position"></el-input>
            </el-form-item>
            <a target="_blank" href="https://api.map.baidu.com/lbsapi/getpoint/index.html" class="btn btn-sm btn-link">
              <el-button type="text" style="padding: 0 0 22px 66%;" size="small"></el-button>
            </a>
          </div>

          <el-form-item label="所属品牌" required :label-width="formLabelWidth" style="width:45%;display: inline-block;">
            <el-form-item prop="org" class="pull-left">
              <el-select placeholder="母品牌" disabled v-model="storeForm.orz_name" @change="fristBrandChange" style="width: 120px">
                <el-option v-for="item in fristBrand" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="brand_id" class="pull-left">
              <el-select placeholder="子品牌" disabled v-model="storeForm.brand_name" style="width: 120px">
                <el-option v-for="item in secondBrand" :key="item.id" :label="item.brand_name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:8%">
          </el-form-item>
          <el-form-item label="客服电话" :label-width="formLabelWidth" style="width:45%;display: inline-block;vertical-align: top;">
            <el-input type="text" disabled v-model="storeForm.service_mobile" :maxlength="50"></el-input>
          </el-form-item>
          <div>
            <el-checkbox style="display:block;" true-label="1" false-label="0" disabled label="配置口碑门店" name="type"></el-checkbox>
          </div>
          <el-form-item label="门店ID" style="width:45%;display: inline-block;" prop="koubei_shop_id" :label-width="formLabelWidth">
            <el-input disabled type="number" placeholder="请输入口碑门店ID" onkeypress="return event.which<=57" v-model="storeForm.koubei_shop_id"></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:8%">
          </el-form-item>
          <el-form-item style="position: relative;width:45%;display: inline-block;" label="手续费率" prop="koubei_fee" :label-width="formLabelWidth">
            <el-input onkeypress="return event.which<=57" disabled type="number" placeholder="口碑渠道手续费率(纯数字)" v-model="storeForm.koubei_fee"></el-input><span
              style="position: absolute;top: 0; right:-12px">%</span>
          </el-form-item>
          <el-form-item label="门店图片" ref="imgUpload" :label-width="formLabelWidth" style=" vertical-align: middle;display: inline-block;width:45%;">
            <img :src="img" height="100px" width="150px" style="vertical-align: middle;">
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:8%;vertical-align: middle;">
          </el-form-item>
          <el-form-item label="门店介绍" :label-width="formLabelWidth" style="vertical-align: middle;display: inline-block;width:45%">
            <el-input disabled type="textarea" :maxlength="999" :rows='4' v-model="storeForm.introduce"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type='text' size="small"> </el-button>
        </div>
      </el-dialog>

      <!-- 状态弹窗 -->
      <el-dialog :close-on-click-modal="false" width="462px" title="选择状态" :visible.sync="stausloadDialog" append-to-body>
        <template>
          <el-radio-group v-model="radio2" style="width:100%;" @change="radios">
            <el-radio label="1">待开业</el-radio>
            <el-radio label="3">已停业</el-radio>
            <el-radio label="2">营业中</el-radio>
            <br />
            <div style="height:20px;"></div>
            <el-radio label="4">待闭店</el-radio>
            <el-radio label="5">已闭店</el-radio>
            <br />
            <div style="height:20px;"></div>

          </el-radio-group>
          <el-button type="primary" style="float: right" size="mini" @click="btnpreservation">保存</el-button>
          <div style="height:20px;"></div>
        </template>

      </el-dialog>

      <!-- 配置对接人弹窗 -->

      <el-dialog :close-on-click-modal="false" width="450px" class="storeDialog" title="对接人管理" :visible.sync="dockingmanagement" @close="callOf('dockingForm')">

        <el-form ref="dockingForm" :model="dockingForm">
          <div style="padding: 0 0 20px 0">门店对接人</div>
          <el-form-item label="姓名">
            <el-select :disabled='!disname' filterable v-model="dockingForm.id" @change='dockchange(1)' style="width: 400px;">
              <el-option v-for="item in dockname" :key="item.id" :label="item.nick" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="电话">
            <el-input disabled style="width: 400px" v-model="dockingForm.phone"></el-input>
          </el-form-item>

          <div style="padding: 0 0 20px 0">总部对接人</div>
          <el-form-item label="姓名">
            <el-select :disabled='!disname' filterable v-model="dockingForms.id" @change='dockchange(2)' style="width: 400px">
              <el-option v-for="item in docknames" :key="item.id" :label="item.nick" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="电话">
            <el-input disabled style="width: 400px" v-model="dockingForms.phone"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click='djSaveClick(1)' v-show='!disname'> 修 改 </el-button>
          <el-button type="primary" size="small" @click='djSaveClick(2)' v-show='disname'> 保 存 </el-button>
        </div>
      </el-dialog>

      <!-- 区域管理弹框 -->
      <el-dialog :close-on-click-modal="false" title="区域管理" :visible.sync="areaInfoDialog">
        <el-table highlight-current-row :data="areaData" border>
          <el-table-column align="center" property="name" label="区域" width="80"></el-table-column>
          <el-table-column align="center" property="num" label="下属机台" width="80"></el-table-column>
          <el-table-column align="center" property="address" label="地址"></el-table-column>
          <el-table-column align="center" property="intro" label="描述"></el-table-column>
          <el-table-column align="center" label="操作" width="50">
            <template slot-scope="scope">
              <el-button @click="areaDelClick(scope.row.id,scope.$index)" type="text" size="small" :disabled="scope.row.num==0?false:true">
                <i class="el-icon-delete"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addAreaDialog=true" size="small"> 新增区域
            <i class="el-icon-circle-plus-outline"></i>
          </el-button>
        </div>
        <el-dialog :close-on-click-modal="false" width="30%" title="新增区域" :visible.sync="addAreaDialog" append-to-body @close="callOf('formAreaAdd')">
          <el-form :model="formAreaAdd" ref="formAreaAdd" :rules="rules" class="demo-form-inline">
            <el-form-item label="区域名称" prop="name">
              <el-input v-model="formAreaAdd.name" placeholder="请输入区域名称"></el-input>
            </el-form-item>
            <el-form-item label="区域描述" prop="intro">
              <el-input type="textarea" :rows="2" placeholder="请输入区域描述" v-model="formAreaAdd.intro"></el-input>
            </el-form-item>
            <el-form-item label="区域地址" prop="address">
              <el-input type="textarea" :rows="2" placeholder="请输入区域地址" v-model="formAreaAdd.address"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="areaAddClick('formAreaAdd')" size="small"> 确 定 </el-button>
          </div>
        </el-dialog>
      </el-dialog>
    </div>

    <!-- 新增编辑门店弹框 -->
    <el-dialog :close-on-click-modal="false" width="812px" class="storeDialog" :title="dialogTitle" :visible.sync="addEditStoreDialog"
      @close="callOf('storeForm')">
      <el-form :model="storeForm" ref="storeForm" :rules="rules" class="demo-form-inline">
        <el-form-item label="门店名称" prop="name" :label-width="formLabelWidth" style="display: inline-block;width:49%;margin-bottom: 0px;">
          <el-input type="text" :rows="2" :maxlength="16" placeholder="请输入门店名称" v-model="storeForm.name"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:4%">
        </el-form-item>
        <el-form-item label="门店编号" prop="serial_number" :label-width="formLabelWidth" style="display: inline-block;width:45%;margin-bottom: 30px;">
          <el-input type="text" :maxlength="16" v-model="storeForm.serial_number"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address" :label-width="formLabelWidth" style="width:49%;display: inline-block;vertical-align:top">
          <dj-region :updateData="reg" :getName="true" :isClear="clearRegion" @provVal="provVal(arguments)" @cityVal="cityVal(arguments)"
            @areaVal="areaVal(arguments)" ref="region"></dj-region>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:4%">
        </el-form-item>
        <el-form-item label="详细地址" prop='address' :label-width="formLabelWidth" style="width:45%;display: inline-block;">
          <el-input type="textarea" :maxlength="32" :rows='4' placeholder="请输入详细地址" v-model="storeForm.address"></el-input>
        </el-form-item>
        <div class="longloats">
          <a target="_blank" href="https://api.map.baidu.com/lbsapi/getpoint/index.html" class="btn btn-sm btn-link">
            <el-button type="text" style="padding: 0px 0 0px 65%;" size="small"> 点击查询经纬度 </el-button>
          </a>
          <el-form-item label="经/纬度" prop="position" :label-width="formLabelWidth" style="width:100%;vertical-align:top;margin-bottom: 0px">
            <el-input type="text" :rows="2" placeholder="经度,纬度的格式填写" v-model="storeForm.position"></el-input>
          </el-form-item>
        </div>
        <el-form-item label="所属品牌" required :label-width="formLabelWidth" style="margin-top: 10px;display: inline-block;width: 49%;">
          <el-form-item prop="org" class="pull-left">
            <el-select placeholder="母品牌" disabled v-model="storeForm.org" @change="fristBrandChange" style="width: 135px">
              <el-option v-for="item in fristBrand" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="brand_id" class="pull-left">
            <el-select placeholder="子品牌" :disabled="mdisshow!='1'" v-model="storeForm.brand_id" style="width: 135px">
              <el-option v-for="item in secondBrand" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:4%">
        </el-form-item>
        <el-form-item prop='service_mobile' label="客服电话" :label-width="formLabelWidth" style="width:45%;display: inline-block;vertical-align: text-bottom;">
          <el-input type="text" v-model="storeForm.service_mobile" :maxlength="16"></el-input>
        </el-form-item>
        <div>
          <el-checkbox style="display:block;padding:10px 0" true-label="1" false-label="0" label="配置口碑门店" name="type" v-model="is_koubei"
            @change="is_koubei_change"></el-checkbox>
        </div>
        <el-form-item label="门店ID" style="width:49%;display: inline-block;" prop="koubei_shop_id" :label-width="formLabelWidth">
          <el-input :disabled="is_koubei!='1'" type="number" placeholder="请输入口碑门店ID" onkeypress="return event.which<=57" :maxlength="32"
            v-model="storeForm.koubei_shop_id"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:4%">
        </el-form-item>
        <el-form-item style="position: relative;width:45%;display: inline-block;" label="手续费率" prop="koubei_fee" :label-width="formLabelWidth">
          <el-input onkeypress="return event.which<=57" :disabled="is_koubei!='1'" type="number" placeholder="口碑渠道手续费率(纯数字)" v-model="storeForm.koubei_fee">
          </el-input><span style="position: absolute;top: 0; right:-12px">%</span>
        </el-form-item>
        <!-- ID和费率提示 -->
        <div class="mid" v-if='ismid'>请输入数字和字母不超过32个</div>
        <div class="kofeilv" v-if='iskofeilv'>请输入100以内纯数字</div>
        <el-form-item label="门店图片" ref="imgUpload" prop="imgList" :label-width="formLabelWidth"
          style=" vertical-align: middle;display: inline-block;width:49%;">
          <el-upload class="avatar-uploader" list-type="picture-card" ref="upload" action="123" :limit="1" :on-exceed="exceedFile" :multiple="true"
            :file-list="imgList" :before-remove="handleBeforeRemove" :on-change="uploadChange" :on-remove="handleRemove" :auto-upload="false"
            accept=".jpg, .jpeg, .png, .JPG, .JPEG">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" style="display: inline-block;width:4%;vertical-align: middle;">
        </el-form-item>
        <el-form-item label="门店介绍" prop="introduce" :label-width="formLabelWidth" style="vertical-align: middle;display: inline-block;width:45%">
          <el-input type="textarea" :maxlength="500" :rows='4' v-model="storeForm.introduce"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="storeSaveClick('storeForm')" size="small" :loading="loading"> 保 存 </el-button>
      </div>
    </el-dialog>

    <!-- 门店关联礼品 -->
    <el-dialog :close-on-click-modal="false" width="30%" title="新增仓库" :visible.sync="storeAssHouseDialog" append-to-body @close="callOf('addHouseForm')">
      <el-form :inline="true" :model="addHouseForm" ref="addHouseForm" :rules="rules" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="addHouseForm.name" placeholder="仓库名称检索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addHouse">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table highlight-current-row :data="houseList" border>
        <el-table-column align="center" property="name" label="仓库名称"></el-table-column>
        <el-table-column align="center" label="删除" width="50">
          <template slot-scope="scope">
            <el-button @click="houseDelClick(scope.row.id,scope.$index)" type="text" size="small" :disabled="scope.row.is_store_main==1?true:false">
              <i class="el-icon-delete"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="hoseSaveClick()"> 保 存 </el-button>
      </div>
    </el-dialog>

    <!-- 文件下载 -->
    <el-dialog :close-on-click-modal="false" width="462px" title="文件下载" :visible.sync="downloadDialog" append-to-body>
      <div class="customHeader">
        <div>门店名称：{{down_store_name}}</div>
      </div>
      <el-form :inline="true" :model="downloadForm" ref="downloadForm" :rules="rules" class="demo-form-inline">
        <el-form-item>
          <el-select placeholder="区域" v-model="downloadForm.area_id" style="width:100px;">
            <el-option v-for="item in downAreaList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="machineDownClick">机台信息对照表下载</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="qrcodeDownClick">二维码下载</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
      <el-button class="pull-right" type="primary" size="small" @click="addEditStoreClick()">新增门店</el-button>
    </div>
  </div>
</template>

<script>
import $ from 'jquery';
import { multiple2decimal, onlyNum } from '@/utils/validate';
const validateVal = (rule, value, callback) => {
  if (!multiple2decimal(value)) {
    callback(new Error('请输入100以内的数字'));
  } else {
    callback();
  }
};
const validateTel = (rule, value, callback) => {
  if (value && !onlyNum(value)) {
    callback(new Error('请输入不超过16个数字'));
  } else {
    callback();
  }
};
const validateID = (rule, value, callback) => {
  if (value && !onlyNum(value)) {
    callback(new Error('请输入数字和字母不超过32个不超过'));
  } else {
    callback();
  }
};

import {
  getmddocking,
  getdocking,
  getList,
  fristBrandList,
  childBrandList,
  getStore,
  getPage,
  areaDetailList,
  areaDel,
  areaAdd,
  storeSave,
  getHouseList,
  getHouse,
  saveHouse,
  delHouse,
  getDownArea,
  machineDown,
  qrcodeDown,
  delStore,
  store_info,
  deleteStatus,
  dockingpreservation,
  upload_store_img,
  setProgram
} from '@/api/information/store';
import { getSts } from '@/api/feedback';
import axios from 'axios';
export default {
  data() {
    const uploadValidator = (rule, value, callback) => {
      if (this.imgList.length === 0) {
        // callback(new Error('请上传图片'));
        callback();
      } else {
        callback();
      }
    };
    return {
      loading: false,
      img: '',
      imgList: [],
      mdockID: '',
      zdockID: '',
      mdisshow: '0',
      detelebtn: true,
      clearRegion: true,
      dockname: [],
      docknames: [],
      reg: {
        prov: '',
        city: '',
        area: ''
      },
      dockobj: {
        store_id: '',
        store_pocking_id: '',
        headquarters_pocking_id: ''
      },
      iskofeilv: false,
      ismid: false,
      dockingForms: {
        id: '',
        phone: ''
      },
      dockingForm: {
        id: '',
        phone: ''
      },
      dockingmanagement: false,
      formLabelWidth: '80px',
      opendetailDia: false,
      isDisabled: false,
      status: [
        {
          id: 0,
          name: '全部'
        },
        { id: 1, name: '待开业' },
        { id: 2, name: '营业中' },
        { id: 3, name: '已停业' },
        { id: 4, name: '待闭店' },
        { id: 5, name: '已闭店' }
      ],
      statusdefa: '营业中',
      stausloadDialog: false, //状态
      listid: '',
      rid: '',
      radio2: '',
      store_list: null,
      brand_list: null,
      bug: false, //暂时无法编辑省市区
      bug_prov: '', //
      bug_city: '', //
      bug_area: '', //
      list: null,
      listLoading: false,
      dialogTitle: '',
      currentPage: 1,
      totalDataNumber: 0,
      fristBrand: [],
      secondBrand: [],
      houseList: [],
      url: '',
      down_store_name: '',
      downAreaList: '',
      formInline: {
        store_id: '',
        prov: '',
        city: '',
        dist: '',
        brand: '',
        category_id: 18,
        status: '2'
      },
      formAreaAdd: {
        sid: '',
        name: '',
        intro: '',
        address: ''
      },
      is_koubei: '0',
      disname: false,
      storeForm: {
        introduce: '',
        is_koubei: '0',
        org: this.$store.getters.orgId,
        koubei_shop_id: '',
        product_fee: '',
        name: '',
        service_mobile: '',
        address: '',
        prov_id: '',
        city_id: '',
        dist_id: '',
        brand_id: '',
        position: '',
        brand_name: '',
        serial_number: '' //门店编号
      },
      addHouseForm: {
        name: '',
        type: 1
      },
      saveHoseForm: {
        house: [],
        store_id: ''
      },
      downloadForm: {
        area_id: '',
        store_id: ''
      },
      rules: {
        introduce: [{ required: true, message: '请填写门店介绍,不超过500字' }],
        imgList: [{ validator: uploadValidator.bind(this) }],
        koubei_shop_id: [{ required: true, validator: validateID, trigger: 'blur' }],
        koubei_fee: [{ required: true, validator: validateVal, trigger: 'blur' }],
        name: [{ required: true, message: '请输入汉字或字母不超过16个，且不能与现有门店重复', trigger: 'blur' }],
        intro: [{ required: true, message: '请输入区域描述', trigger: 'blur' }],
        address: [
          {
            required: true,
            message: '请输入不超过32个汉字数字',
            trigger: 'blur'
          }
        ],
        org: [{ required: true, message: '请选择母品牌', trigger: 'change' }],
        brand_id: [{ required: true, message: '请选择子品牌', trigger: 'change' }],
        service_mobile: [{ required: false, message: '请选择', trigger: 'blur' }],
        position: [{ required: true, message: '请按‘经度，纬度’格式输入经纬度', trigger: 'blur' }],
        serial_number: [{ required: true, message: '请输入字母与符号不超过16个，且不能与现有门店编号重复', trigger: 'blur' }]
      },
      areaData: [],
      areaInfoDialog: false,
      addAreaDialog: false,
      addEditStoreDialog: false,
      storeAssHouseDialog: false,
      downloadDialog: false,
      userinfo: JSON.parse(localStorage.getItem('USER_INFO')),
      id: ''
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.store_list) {
        vm.brandChangeF();
      }
    });
  },
  watch:{
    "storeForm.position":{
      handler(oldValue,newValue){
         if(this.storeForm.position.indexOf('/') != -1){
           this.storeForm.position = this.storeForm.position.replace('/',',');
         }
      },deep:true
    }
  },
  created() {
    getmddocking({}).then(res => {
      this.dockname = res;
    });
    getdocking({ nick: '' }).then(res => {
      this.docknames = res;
    });
  },
  methods: {
    uploadChange(file, fileList) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/jpg' || 'image/png';
      const isLt1M = file.size / 1024 / 1024 < 2;
      // this.$refs.ruleForm.clearValidate(['imgList']);
      if (!isIMAGE) {
        this.$message.error('上传图片格式只能为jpg、png、jpeg!');
        fileList.splice(fileList.length - 1, 1);
        return;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 2MB!');
        fileList.splice(fileList.length - 1, 1);
        return;
      }
      this.imgList = fileList;
    },
    handleBeforeRemove(file, fileList) {},
    handleRemove(file, fileList) {
      this.imgList = fileList;
    },
    exceedFile(files, fileList) {
      this.$message.error('只能上传1张图片');
    },
    saveDialog(){
      if (this.imgList.length === 0) {
        storeSave(this.storeForm, this.url).then(response => {
          this.ismid = false;
          this.iskofeilv = false;
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.loading = false;
            this.handleCurrentChange(this.currentPage);
          }
          this.addEditStoreDialog = false;
          this.$refs.storeForm.resetFields();
        }).catch(res=>{
          this.loading = false;
        })
      } else {
        this.uploadFile();
      }
    },
    uploadFile() {
      const imgList = this.imgList;
      let folder_name = location.host == 'scfy.i3020.com' || location.host == 'ims.i3020.com' ? 'scsrc/store_gift' : 'scsrc/store_gift_dev';
      getSts({}, 2).then(response => {
        let host = 'https://img.hahaipi.com';
        let policyText = {
          expiration: '2022-01-01T12:00:00.000Z', //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
          conditions: [
            ['content-length-range', 0, 1048576000] // 设置上传文件的大小限制
          ]
        };
        let upLoadData = {};
        let progress = 0;
        upLoadData.img_list = [];
        upLoadData.store_id = this.id;
        imgList.forEach((val, i) => {
          let imgSuffix = val.name.split('.');
          let suffix = imgSuffix[imgSuffix.length - 1];
          let policyBase64 = Base64.encode(JSON.stringify(policyText));
          let bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, response.AccessKeySecret, { asBytes: true });
          let signature = Crypto.util.bytesToBase64(bytes);
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };
          let date = new Date();
          let month = date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
          let day = date.getDate() < 9 ? '0' + date.getDate() : date.getDate();
          let h = date.getHours() < 9 ? '0' + date.getHours() : date.getHours();
          let min = date.getMinutes() < 9 ? '0' + date.getMinutes() : date.getMinutes();
          let s = date.getSeconds() < 9 ? '0' + date.getSeconds() : date.getSeconds();
          let dateYMD = `${date.getFullYear()}${month}${day}`;
          let dateHMS = `${h}${min}${s}`;
          let data = new FormData();
          let imgName = `${folder_name}/${this.id}/${dateYMD}${dateHMS}${this.S4(10000, 99999)}.${suffix}`;
          data.append('key', imgName);
          data.append('policy', policyBase64);
          data.append('OSSAccessKeyId', response.AccessKeyId);
          data.append('success_action_status', 200);
          data.append('x-oss-security-token', response.SecurityToken);
          data.append('signature', signature);
          data.append('file', val.raw);
          upLoadData.img_list.push({ img: imgName, gift_id: this.id });
          axios
            .post(host, data, config)
            .then(res => {
              progress++;
              if (progress == imgList.length) {
                if (suffix == 'jpg' || suffix == 'png' || suffix == 'jpeg') {
                  upload_store_img(upLoadData).then(res => {});
                  // this.loading = false;
                }
                storeSave(this.storeForm, this.url).then(response => {
                  this.ismid = false;
                  this.iskofeilv = false;
                  this.$message({
                    type: response.code == 1 ? 'success' : 'error',
                    message: response.message
                  });
                  if (response.code == 1) {
                    this.loading = false;
                    this.handleCurrentChange(this.currentPage);
                  }
                  this.addEditStoreDialog = false;
                  this.$refs.storeForm.resetFields();
                });
              }
            })
            .catch(res => {
              this.$message({
                type: 'error',
                message: JSON.stringify(res)
              });
            });
        });
      }).catch(()=>{
        this.loading = false;
      });
    },
    S4(m, n) {
      return Math.floor(Math.random() * (m - n) + n);
    },
    //对接人修改
    djSaveClick(i) {
      if (i == 1) {
        this.disname = true;
      } else {
        this.presevrbtn();
      }
    },
    //门店对接人保存
    presevrbtn() {
      if (!this.dockingForms.id || !this.dockingForm.id) {
        this.$message.error('请完善信息再保存!');
        return;
      }
      if (this.dockingForms.id == this.dockingForm.id) {
        this.$message.error('门店对接人和总部对接人不能为同一人!');
        return;
      }
      if (this.dockingForm.id == this.dockobj.store_pocking_id && this.dockingForms.id == this.dockobj.headquarters_pocking_id) {
        this.dockingmanagement = false;
        return;
      }
      let data = {
        store_id: this.dockobj.id,
        store_pocking_id: this.dockingForm.id,
        headquarters_pocking_id: this.dockingForms.id
      };
      dockingpreservation(data).then(res => {
        if (res.code == 1) {
          this.$message.success(res.message);
          this.fetchData();
        }
        this.detelebtn = true;
        this.dockingmanagement = false;
      });
    },
    //获取选中的对接人
    dockchange(num) {
      if (num == 1 || num == 0) {
        let arr = [];
        arr = this.dockname.filter(item => item.id == this.dockingForm.id);
        this.dockingForm.phone = arr[0].phone;
      } else {
        let arr = [];
        arr = this.docknames.filter(item => item.id == this.dockingForms.id);
        this.dockingForms.phone = arr[0].phone;
        this.zdockID = arr[0].id; //总部对接人ID
      }
    },
    //点击配置对接人
    toconfigpeople(obj) {
      this.dockobj.id = obj.id;
      this.dockobj.store_pocking_id = obj.store_pocking_id == 0 ? '' : obj.store_pocking_id;
      this.dockobj.headquarters_pocking_id = obj.headquarters_pocking_id == 0 ? '' : obj.headquarters_pocking_id;
      let store_pocking_id = obj.store_pocking_id == 0 ? '' : obj.store_pocking_id;
      this.$set(this.dockingForm, 'id', store_pocking_id);
      this.dockingForm.phone = obj.store_pocking_phone;
      let headquarters_pocking_id = obj.headquarters_pocking_id == 0 ? '' : obj.headquarters_pocking_id;
      this.$set(this.dockingForms, 'id', headquarters_pocking_id);
      this.dockingForms.phone = obj.headquarters_pocking_phone;
      if (!this.dockingForm.id && !this.dockingForms.id) {
        this.disname = true;
      }
      this.dockingmanagement = true;
    },
    //点击查看详细
    detail(id) {
      store_info({ store_id: id }).then(response => {
        this.storeForm = response;
        if (this.storeForm.koubei_fee == 0) {
          this.storeForm.koubei_fee = '';
        }
        if (this.storeForm.koubei_shop_id == 0) {
          this.storeForm.koubei_shop_id = '';
        }
        let org_name = localStorage.getItem('orgName_' + this.userinfo.id);
        this.storeForm.orz_name = org_name;
        this.is_koubei = response.koubei_shop_id * 1 > 0 ? '1' : '0';
        this.storeForm.position = response.longitude + ',' + response.latitude;
        this.bug = true;
        this.bug_prov = response.prov_name;
        this.bug_city = response.city_name;
        this.bug_area = response.dist_name;
        this.img = response.img;
      });
      this.opendetailDia = true;
    },
    //状态
    dialogVisibles(id, data) {
      this.radio2 = data.s_status;
      this.listid = id; //先保存点击的ID
      this.stausloadDialog = true;
    },
    radios() {
      this.rid = this.radio2;
    },
    //保存
    btnpreservation() {
      let arr = this.list;
      deleteStatus({ store_id: this.listid, status: this.rid }).then(res => {
        if (res.code == 1) {
          this.stausloadDialog = false;
          arr.map(res => {
            if (res.id == this.listid) {
              res.s_status = this.rid;
            }
          });
          this.$message({
            message: '修改成功',
            type: 'success'
          });
        }
      });
    },
    brandChangeF() {
      getStore({ category_id: 18 }).then(response => {
        this.store_list = response;
        let data = response.filter(res => res.id == this.$store.getters.optionId);
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        }
        this.fetchData();
      });
    },
    // 子组件传过来的省
    provVal(val) {
      this.addEditStoreDialog ? (this.storeForm.prov_id = val[0]) : (this.formInline.prov = val);
      this.addEditStoreDialog ? (this.storeForm.prov_name = val[1]) : (this.formInline.prov = val);
    },
    // 子组件传过来的市
    cityVal(val) {
      this.addEditStoreDialog ? (this.storeForm.city_id = val[0]) : (this.formInline.city = val);
      this.addEditStoreDialog ? (this.storeForm.city_name = val[1]) : (this.formInline.city = val);
    },
    // 子组件传过来的区
    areaVal(val) {
      this.addEditStoreDialog ? (this.storeForm.dist_id = val[0]) : (this.formInline.dist = val);
      this.addEditStoreDialog ? (this.storeForm.dist_name = val[1]) : (this.formInline.dist = val);
    },
    fristBrandChange(id) {
      this.formInline.brand = '';
      childBrandList(id).then(response => {
        if (this.addEditStoreDialog) {
          this.storeForm.brand_id = '';
        }
        this.secondBrand = response;
      });
    },

    searchClick() {
      this.fetchData();
    },
    getFristBrand() {
      fristBrandList().then(response => {
        this.fristBrand = response;
      });
    },
    is_koubei_change() {
      this.ismid = false;
      this.iskofeilv = false;
      this.storeForm.koubei_shop_id = '';
      this.storeForm.koubei_fee = '';
    },
    // 新增编辑门店
    addEditStoreClick(id, index, date) {
      this.id = id;
      this.url = id ? '/Store/edit' : '/Store/create';
      this.bug = false;
      this.getFristBrand();
      childBrandList().then(response => {
        this.secondBrand = response;
      });
      this.dialogTitle = id ? '编辑门店' : '添加门店';
      this.addEditStoreDialog = true;
      if (id) {
        this.storeForm.service_mobile = '';
        this.imgList = [];
        this.mdisshow = '0';
        this.storeForm.prov_id = date.prov_name;
        this.storeForm.city_id = date.city_name;
        this.storeForm.dist_id = date.dist_name;
        store_info({ store_id: id }).then(response => {
          this.storeForm = response;
          if (this.storeForm.koubei_fee == 0) {
            this.storeForm.koubei_fee = '';
          }
          if (this.storeForm.koubei_shop_id == 0) {
            this.storeForm.koubei_shop_id = '';
          }
          this.is_koubei = response.koubei_shop_id * 1 > 0 ? '1' : '0';
          this.$set(this.storeForm,'position',response.longitude + ',' + response.latitude);
          // this.storeForm.position = response.longitude + ',' + response.latitude;
          if (response.img != null) {
            this.imgList.push({ name: response.id, url: response.img });
          }
          this.reg = {
            prov: response.prov_id,
            city: response.city_id,
            area: response.dist_id
          };
        });
      } else {
        this.mdisshow = '1';
        this.is_koubei = '0';
        this.storeForm.koubei_shop_id = '';
        this.storeForm.koubei_fee = '';
        this.storeForm.name = '';
        this.storeForm.address = '';
        this.storeForm.prov_id = '';
        this.storeForm.city_id = '';
        this.storeForm.dist_id = '';
        this.storeForm.brand_id = '';
        this.storeForm.position = '';
        this.storeForm.service_mobile = '';
        this.storeForm.org_name = '';
        this.storeForm.serial_number = '';
        this.storeForm.introduce = '';
        this.imgList = [];
        setTimeout(() => {
          this.$refs.region.reset();
        }, 0);
      }
    },
    storeSaveClick(formName) {
      this.$refs[formName].validate(vaild => {
        if (this.is_koubei == 1) {
          if (this.storeForm.koubei_shop_id == '') {
            this.ismid = true;
            return;
          }
          if (this.storeForm.koubei_fee == '') {
            this.iskofeilv = true;
            return;
          }
        } else {
          this.ismid = false;
          this.iskofeilv = false;
        }
        if (this.storeForm.org == 0 || this.storeForm.brand_id == 0) {
          this.$message({ type: 'error', message: '请选择正确的品牌再保存' });
          return;
        }
        if (vaild) {
          this.loading = true;
          this.saveDialog();
          // this.uploadFile();
        }
      });
    },
    // 关联仓库
    assHouseClick(id) {
      this.saveHoseForm.store_id = id;
      this.houseList = [];
      this.addHouseForm.name = '';
      this.saveHoseForm.house = [];
      this.storeAssHouseDialog = true;
      getHouseList({ store_id: id }).then(response => {
        this.houseList = response;
      });
    },
    // 新增仓库
    addHouse() {
      getHouse(this.addHouseForm).then(response => {
        if (response.length > 0) {
          if (this.saveHoseForm.house.length == 0) {
            this.saveHoseForm.house.push(response[0]);
            this.houseList.push(response[0]);
            return;
          }
          for (let i = 0; i < this.saveHoseForm.house.length; i++) {
            if (this.saveHoseForm.house[i].id == response[0].id) {
              this.$message({
                type: 'error',
                message: '此仓库已添加!'
              });
              return;
            }
          }
          this.saveHoseForm.house.push(response[0]);
          this.houseList.push(response[0]);
        } else {
          this.$message({
            type: 'error',
            message: '无此仓库请重新查询!'
          });
        }
      });
    },
    // 仓库删除
    houseDelClick(id, index) {
      delHouse({ id: id }).then(response => {
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message
        });
        if (response.code == 1) {
          this.saveHoseForm.house.splice(index, 1);
          this.houseList.splice(index, 1);
        }
      });
    },
    // 关联仓库保存
    hoseSaveClick() {
      if (this.saveHoseForm.house.length > 0) {
        const houseArr = [];
        for (let i = 0; i < this.saveHoseForm.house.length; i++) {
          houseArr.push(this.saveHoseForm.house[i].id);
        }
        saveHouse({ house: houseArr.join(), store_id: this.saveHoseForm.store_id }).then(response => {
          if (response.code == 1) {
            this.storeAssHouseDialog = false;
            this.$message({
              type: 'success',
              message: response.message
            });
          }
        });
      } else {
        this.$message({
          type: 'error',
          message: '请先添加仓库！'
        });
      }
    },
    // 下载
    downloadClick(id, name) {
      this.down_store_name = name;
      this.downloadForm.store_id = id;
      this.downloadForm.area_id = '';
      this.downloadDialog = true;
      getDownArea({ store_id: id }).then(response => {
        this.downAreaList = response;
        this.listLoading = false;
      });
    },
    // 机台表下载
    machineDownClick() {
      if (!this.downloadForm.area_id) {
        this.$message({
          type: 'error',
          message: '请先选择区域！'
        });
        return;
      }
      machineDown(this.downloadForm);
    },
    // 二维码下载
    qrcodeDownClick() {
      if (!this.downloadForm.area_id) {
        this.$message({
          type: 'error',
          message: '请先选择区域！'
        });
        return;
      }
      qrcodeDown(this.downloadForm);
    },
    //删除门店
    delStoreClick(id, index) {
      this.$confirm('此操作删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delStore({ id: id }).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.list.splice(index, 1);
          }
        });
      });
    },
    //查看区域
    areaDetailDelClick(id) {
      this.areaInfoDialog = true;
      areaDetailList(id).then(response => {
        this.formAreaAdd.sid = id;
        this.areaData = response;
        this.listLoading = false;
      });
    },
    // 配置微信、支付宝小程序
    changeClick(row,type){
      if(type == 1){
        if(!row.is_switch){
          this.$confirm(`是否确定关闭微信小程序`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(()=>{
            openProgram()
          }).catch(() => {
            row.is_switch = true;
          });
        }else{
          openProgram()
        }
      }else{
        if(!row.zfb_switch){
          this.$confirm(`是否确定关闭支付宝小程序`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(()=>{
            openProgram()
          }).catch(() => {
            row.zfb_switch = true;
          });
        }else{
          openProgram()
        }
      }
      function openProgram() {
        setProgram({store_id:row.id,is_program:row.is_switch?1:0,is_zfb_program:row.zfb_switch?1:0}).then(res=>{
          if(res.code==1){
            this.$message.success(res.message);
          }
        })
      }
    },
    // 删除区域
    areaDelClick(id, index) {
      this.$confirm('此操作删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        areaDel(id).then(response => {
          if (response.code == 1) {
            this.areaData.splice(index, 1);
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
        });
      });
    },
    // 增加区域
    areaAddClick(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          areaAdd(this.formAreaAdd).then(response => {
            this.addAreaDialog = false;
            this.$refs[formName].resetFields();
            areaDetailList(this.formAreaAdd.sid).then(response => {
              this.areaData = response;
            });
          });
        }
      });
    },
    //关闭弹框重置
    callOf(formName) {
      this.dockingForms = {
        name: '',
        region: ''
      };
      this.dockingForm = {
        name: '',
        region: ''
      };
      this.detelebtn = true;
      this.disname = false;
      this.$refs[formName].resetFields();
    },
    getData(data){
      data.forEach(val=>{
        val.is_switch=val.is_program==1;
        val.zfb_switch=val.is_zfb_program==1;
      })
      this.list=data;
    },
    async fetchData() {
      this.list = [];
      this.listLoading = true;
      this.currentPage = 1;
      this.formInline.status = this.statusdefa == '营业中' ? '2' : this.statusdefa;
      try {
        let page = await getPage(this.formInline);
        this.totalDataNumber = page * 20;
        if (page > 0) {
          let data = await getList(this.formInline);
          this.getData(data);
          this.listLoading = false;
        } else {
          this.listLoading = false;
        }
      } catch (error) {
        this.listLoading = false;
      }
    },
    async handleCurrentChange(val) {
      this.listLoading = true;
      let data = await getList(this.formInline, val);
      this.getData(data);
      this.listLoading = false;
    }
  }
};
</script>

<style scoped>
.longloat {
  position: absolute;
  top: 35%;
  left: 2.5%;
  width: 352px;
}
.longloats {
  position: absolute;
  top: 29%;
  left: 2.5%;
  width: 352px;
}
.mid,
.kofeilv {
  font-size: 12px;
  color: #f56c6c;
}
.mid {
  position: absolute;
  top: 80%;
  left: 13%;
}
.kofeilv {
  position: absolute;
  top: 80%;
  left: 64.5%;
}
.el-form-item /deep/ .el-upload--picture-card {
  width: 100px;
  height: 100px;
}

.el-form-item /deep/ .el-upload {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.el-form-item /deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  transition: none !important;
}
</style>
